/**
 * This file is released under the GNU General Public License.
 * Refer to the COPYING file distributed with this package.
 *
 * Copyright (c) 2008-2009 WURFL-Pro srl
 */
package net.sourceforge.wurfl.browser.server;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sourceforge.wurfl.core.CapabilityNotDefinedException;
import net.sourceforge.wurfl.core.Device;
import net.sourceforge.wurfl.core.MarkUp;
import net.sourceforge.wurfl.core.WURFLHolder;
import net.sourceforge.wurfl.core.WURFLManager;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 
 * @author Luca Passani
 * 
 * @version $Id: HelloWorld.java 384 2009-11-17 14:48:24Z filippo.deluca $
 */
public class HelloWorld extends HttpServlet {

	/** Serial */
	private static final long serialVersionUID = 10L;

	private static final String XHTML_ADV = "xhtmladv.jsp";
	private static final String XHTML_SIMPLE = "xhtmlmp.jsp";
	private static final String CHTML = "chtml.jsp";
	private static final String WML = "wml.jsp";

	/** Logger */
	private final Log log = LogFactory.getLog(getClass());
	
	private static final boolean REDIRECT = false;

	/**
	 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
	 * methods.
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 */
	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		WURFLHolder wurflHolder = (WURFLHolder) getServletContext()
				.getAttribute("net.sourceforge.wurfl.core.WURFLHolder");

		WURFLManager wurfl = wurflHolder.getWURFLManager();

		Device device = wurfl.getDeviceForRequest(request);
		
		log.debug("Device: " + device.getId());
		log.debug("Capability: " + device.getCapability("preferred_markup"));

		MarkUp markUp = device.getMarkUp();

		String jspView = null;

		if (MarkUp.XHTML_ADVANCED.equals(markUp)) {
			jspView = XHTML_ADV;
		} else if (MarkUp.XHTML_SIMPLE.equals(markUp)) {
			jspView = XHTML_SIMPLE;
		} else if (MarkUp.CHTML.equals(markUp)) {
			jspView = CHTML;
		} else if (MarkUp.WML.equals(markUp)) {
			jspView = WML;
		}

		
		log.info("View: " + jspView);

		// MIME type is decided by JSP. Only in case of XHTML we will need to
		// multi-serve
		// i.e text/html vs application/xml+xhtml vs
		// application/vnd.wap.xml+xhtml
		if (markUp == MarkUp.XHTML_ADVANCED || markUp == MarkUp.XHTML_SIMPLE) {
			String contentType = "text/html";
			try {
				contentType = device
						.getCapability("xhtmlmp_preferred_mime_type");
			} catch (CapabilityNotDefinedException e) {
				throw new RuntimeException(
						"Somethingh is seriously wrong with your WURFL:"
								+ e.getLocalizedMessage(), e);
			}

			request.setAttribute("contentType", contentType);
			log.debug("ContentType: " + contentType);
		}

		request.setAttribute("markUp", markUp);
		request.setAttribute("device", device);

		if( REDIRECT )
		{
			request.getRequestDispatcher("WEB-INF/jsp/" + jspView).forward(request,
					response);
		}
		else
		{
			response.setContentType("text/html");
			OutputStream os = response.getOutputStream();
			
			StringBuffer buffer = new StringBuffer();
			buffer.append("User-Agent: " + request.getHeader("user-agent"));
			buffer.append("\n<br/>WURFL device id: " + device.getId() + "\n<br/>");
			
			buffer.append("\n<br/>\n<br/>Select Capabilities:\n<br/>");
			buffer.append("\n<br/>preferred_markup: " + device.getCapability("preferred_markup"));
			buffer.append("\n<br/>j2me_midp_1_0: " + device.getCapability("j2me_midp_1_0"));
			buffer.append("\n<br/>j2me_cldc_1_0: " + device.getCapability("j2me_cldc_1_0"));
			buffer.append("\n<br/>j2me_midp_2_0: " + device.getCapability("j2me_midp_2_0"));
			buffer.append("\n<br/>j2me_cldc_1_1: " + device.getCapability("j2me_cldc_1_1"));
			
			buffer.append("\n<br/>\n<br/>All Capabilities:\n<br/>");
			Map deviceCapabilities = device.getCapabilities();
			Set keys = deviceCapabilities.keySet();
			Iterator keysIterator = keys.iterator();
			while( keysIterator.hasNext() )
			{
				Object key = keysIterator.next();
				Object value = deviceCapabilities.get(key);
				buffer.append("\n<br/>" + key.toString() + ": " + value.toString());
			}
			
			os.write(buffer.toString().getBytes());
		}
		
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

}
